<template>
  <div class="shop-add-group">
    <el-row>
      <el-col :span="16" :offset="4">
        <el-form label-width="100px" label-position="right" :model="shopInfo">
          <el-form-item label="商户名">
            <el-input v-model="shopInfo.name" placeholder="请输入商户名"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-autocomplete style="width: 100%" v-model="shopInfo.address" :trigger-on-focus="false"
                             :fetch-suggestions="querySearch" placeholder="请输入店铺地址"></el-autocomplete>
            <span>当前城市:{{ city.name }}</span>
          </el-form-item>
          <el-form-item label="商铺简介">
            <el-input type="textarea" v-model="shopInfo.description" placeholder="请输入商铺简介" resize="none" maxlength="50"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="宣传口号">
            <el-input type="textarea" v-model="shopInfo.promotion_info" placeholder="请输入宣传口号" resize="none"
                      maxlength="50" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="shopInfo.phone" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="营业时间">
            <el-time-select placeholder="开始时间" v-model="shopInfo.startTime" :picker-options="{
              start:'05:00',
              end:'23:00'
            }"></el-time-select>
            -
            <el-time-select placeholder="结束时间" v-model="shopInfo.endTime" :picker-options="{
              start:'05:00',
              end:'23:00',
              minTime:shopInfo.startTime
            }"></el-time-select>
          </el-form-item>
          <el-form-item label="平台税(%)">
            <el-input placeholder="请输入平台抽取税率" v-model="shopInfo.platform_rate"></el-input>
          </el-form-item>
          <el-form-item label="配送费">
            <el-input-number :max="15" :min="2" v-model="shopInfo.float_delivery_fee"></el-input-number>
          </el-form-item>
          <el-form-item label="起送价格">
            <el-input-number :max="200" :min="15" :step="5"
                             v-model="shopInfo.float_minimum_order_amount"></el-input-number>
          </el-form-item>
          <el-form-item label="商户分类">
            <el-cascader v-model="shopInfo.categorySelect" :options="categoryList"
                         :props="{children:'sub_categories',label:'name',value:'name'}"
                         @change="formatterCategory"></el-cascader>
          </el-form-item>
          <el-form-item label="商户特色">
            <el-switch class="switch-style" v-model="shopInfo.is_premium" active-text="品牌保障"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.deliveryMode" active-text="蜂鸟转送"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.bao" active-text="超时赔付"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.zhun" active-text="准时达"></el-switch>
            <el-switch class="switch-style" v-model="shopInfo.piao" active-text="开发票"></el-switch>
          </el-form-item>
          <el-form-item label="店铺头像">
            <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="imagePathSuccess"
                       :headers="uploadHeader" :show-file-list="false">
              <el-button type="success" icon="el-icon-folder-opened">上传</el-button>
            </el-upload>
            <el-image v-if="imagePath.showImage" :src="imagePath.imagePath" style="width: 100px;height: 100px"
                      :preview-src-list="imagePath.imagePrevList">
            </el-image>
          </el-form-item>
          <el-form-item label="营业执照">
            <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="businessPathSuccess"
                       :headers="uploadHeader" :show-file-list="false">
              <el-button type="success" icon="el-icon-folder-opened">上传</el-button>
            </el-upload>
            <el-image v-if="businessPath.showImage" :src="businessPath.imagePath" style="width: 100px;height: 100px"
                      :preview-src-list="businessPath.imagePrevList">
            </el-image>
          </el-form-item>
          <el-form-item label="从业资格证">
            <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="cateringPathSuccess"
                       :headers="uploadHeader" :show-file-list="false">
              <el-button type="success" icon="el-icon-folder-opened">上传</el-button>
            </el-upload>
            <el-image v-if="cateringPath.showImage" :src="cateringPath.imagePath" style="width: 100px;height: 100px"
                      :preview-src-list="cateringPath.imagePrevList">
            </el-image>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="resetForm">重置</el-button>
            <el-button type="warning" @click="submitForm">保存</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>


<script>
const initShop = {
  name: '',
  address: '',
  description: '',
  promotion_info: '',
  phone: '',
  startTime: '',
  endTime: '',
  platform_rate: '',
  float_delivery_fee: 5,
  float_minimum_order_amount: 20,
  categorySelect: [],
  category: '',
  is_premium: true,
  deliveryMode: true,
  bao: true,
  zhun: true,
  piao: true,
  image_path: '',
  business_license_image: '',
  catering_service_license_image: ''

}

export default {
  name: 'addShopInfo',
  data() {
    return {
      shopInfo: {...initShop},
      city: {},
      categoryList: [],
      uploadPath: 'http://192.168.26.105:8082/file',
      uploadHeader: {
        Authorization: ''
      },
      imagePath: {
        imagePath: '',
        showImage: false,
        imagePrevList: []
      },
      businessPath: {
        imagePath: '',
        showImage: false,
        imagePrevList: []
      },
      cateringPath: {
        imagePath: '',
        showImage: false,
        imagePrevList: []
      },
    }
  },
  methods: {
    getCity() {
      this.$http.get('/v1/cities', {type: 'guess'}).then(({data}) => {
        if (data.code === 20000) {
          this.city = data.data
        }
      })
    },
    querySearch(query, callback) {
      this.$http.get('v1/pois', {city_id: this.city.id, keyword: query}).then(({data}) => {
        if (data.code === 20000) {
          const valueList = data.data.map(item => {
            return {
              value: item.address
            }
          })
          callback(valueList)
        }
      })
    },
    getCategory() {
      this.$http.get('shopping/v2/restaurant/category').then(({data}) => {
        if (data.code === 20000) {
          this.categoryList = data.data
        }
      })
    },
    formatterCategory(value) {
      this.shopInfo.category = value.join('/')
    },
    beforeUpload(file) {
      const isType = (file.type === 'image/jpeg') || (file.type === 'image/png')
      if (!isType) {
        this.$message({
          message: '请上传正确格式的图片',
          type: 'error'
        })
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message({
          message: '上传文件不能超过5M',
          type: 'error'
        })
      }
      return isType && isLt2M
    },
    imagePathSuccess(data) {
      if (data.code === 20000) {
        this.imagePath.showImage = true
        this.imagePath.imagePath = 'http://192.168.26.105:8082/file/getImgStream?fileName=' + data.data.realFileName
        this.imagePath.imagePrevList = [this.imagePath.imagePath]
        this.shopInfo.image_path = data.data.realFileName
      }
    },
    businessPathSuccess(data) {
      if (data.code === 20000) {
        this.businessPath.showImage = true
        this.businessPath.imagePath = 'http://192.168.26.105:8082/file/getImgStream?fileName=' + data.data.realFileName
        this.businessPath.imagePrevList = [this.businessPath.imagePath]
        this.shopInfo.business_license_image = data.data.realFileName
      }
    },
    cateringPathSuccess(data) {
      if (data.code === 20000) {
        this.cateringPath.showImage = true
        this.cateringPath.imagePath = 'http://192.168.26.105:8082/file/getImgStream?fileName=' + data.data.realFileName
        this.cateringPath.imagePrevList = [this.cateringPath.imagePath]
        this.shopInfo.catering_service_license_image = data.data.realFileName
      }
    },
    resetForm () {
      this.shopInfo = { ...initShop }
    },
    submitForm() {
      this.loading=this.$loading({text:'提交中...'})
      this.shopInfo.activitiesJson = JSON.stringify([{ icon_name: '减', name: '满减优惠', description: '满30减5，满60减8' }])
      this.$http.post('shopping/addShop',this.shopInfo).then(({data})=>{
        this.loading.close()
        if (data.code=20000){
          this.$alert('保存成功',{type:"success"}).then(()=>{
            this.resetForm()
            this.$router.push("shop")
          })
        }else{
          this.$alert("保存失败",{type:"error"})
        }
      })
    },
    init(){
      if (this.$route.query.id){
        this.$http.get('/shopping/restaurant/'+this.$route.query.id).then(({data})=>{
          if (data.code===20000){
            const shop=data.data
            console.log(shop)
            this.shopInfo={
              name: shop.name,
              description: shop.description,
              address: shop.address,
              promotion_info: shop.promotion_info,
              phone: shop.phone,
              platform_rate: shop.platform_rate,
              float_delivery_fee: shop.float_delivery_fee,
              float_minimum_order_amount: shop.float_minimum_order_amount,
              startTime: shop.opening_hours[0].split('/')[0],
              endTime: shop.opening_hours[0].split('/')[1],
              category: shop.category,
              categorySelect: shop.category.split('/'),
              is_premium: shop.is_premium === 'true',
              deliveryMode: shop.delivery_mode !== undefined,
              zhun: shop.supports && shop.supports.filter(item => item.icon_name === '准').length === 1,
              bao: shop.supports && shop.supports.filter(item => item.icon_name === '保').length === 1,
              piao: shop.supports && shop.supports.filter(item => item.icon_name === '票').length === 1

            }
          }
        })
      }
    }

  },

  created() {
    this.init()
    this.$nextTick(() => {
      this.getCity()
      this.getCategory()
      this.uploadHeader.Authorization = this.$cookies.get('token')
    })
  }
}
</script>

<style scoped lang="scss">
.switch-style {
  margin-right: 35px;
}
</style>
